package cii_lib_graph;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import testy.TestHardware;
import cii_functions.FCII_TIMER;
import cii_functions.FCII_interfaceReader;
import cii_lib.CCII_ACCESS_INTERF;
import cii_lib.CCII_COMPONENT;
import cii_lib.CIIdata;
import cii_lib_graph.elements.GciiToggleButton;
import cii_lib_graph.elements.ProgressBar;

import componentEnhancement.CiiDataContainer;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class GCII_TIMER extends javax.swing.JFrame implements plugins.ICIIGraphicable {

	private static final Logger log = LoggerFactory.getLogger(GCII_TIMER.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 3912280692828991987L;
	private Vector<GciiToggleButton> bitsTB = new Vector<GciiToggleButton>();
	private JPanel gTimerPanel;
	private GInterfaceTerminal countint = new GInterfaceTerminal();
	private GInterfaceTerminal limit = new GInterfaceTerminal(); 
	
	private int groupWidth = 0;
	private double bitsValue = 0L;
	private GCII_BITSGroup gCII_BITSGroup1;
	private JTextField delayField;
	private ProgressBar jProgressBar;
	private JLabel jLabel2;
	private JTextField jTextField1;
	private JTextField countField;
	private JLabel jLabel1;
	
	private FCII_TIMER timerFunc = null;
	private JMenuItem menuStop;
	private JMenuItem menuRead;
	private JPopupMenu jPopupMenu1;
	private JLabel jLabel4;
	private JLabel jLabel3;
	private JScrollPane jScrollPaneBits;
	private JScrollPane jScrollPane1;
	
	private Thread thCount;
	private Runnable readerC; 
	/**
	* Auto-generated main method to display this JFrame
	*/
	public void testGUI() {
//		final GCII_TIMER inst = new GCII_TIMER();
//		inst.setVisible(true);
		JFrame frame = this;
		frame.getContentPane().add(gTimerPanel);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.setSize(285, 364);
		frame.setPreferredSize(new Dimension(286, 395));
		frame.pack();
		frame.setVisible(true);
		for (int i=0;i<=100;i++) {
			final int per = i;
			try {
		        SwingUtilities.invokeLater(new Runnable() {
		          public void run() {
		            getJProgressBar().setValue(per);
		            getJProgressBar().setString(per+" %");
		          }
		        });
		        java.lang.Thread.sleep(65);
		      } catch (InterruptedException e) {
		        ;
		      }
		}
//		SwingUtilities.
	}
	
	public GCII_TIMER() {
		super();
		initGUI();
	}
	
	public GCII_TIMER(final FCII_TIMER fctim) {
		super();
		timerFunc = fctim;
		initGUI();
		initRead();
	}
	
	public void initRead() {
		log.debug("reading init");
		readerC = new FCII_interfaceReader(countint,(CiiDataContainer)getJProgressBar(),300);
		
		thCount = new Thread(readerC);
		TestHardware.incrementType=0;
//		thCount.start();
	}
	
	public double countValue(int pos, boolean val, JTextField valfield){
		if (val) {
			bitsValue = bitsValue + Math.pow(2, pos);
		} else {
			bitsValue = bitsValue - Math.pow(2, pos);
		}
		if (bitsValue<0) {
			valfield.setText(""+(long)bitsValue);
			return 0; 
		}
		else {
			valfield.setText(""+(long)bitsValue);
			return bitsValue;
		}
	}
	
//	public void testGUI() {
//		JFrame frame = new JFrame();
//		frame.getContentPane().add(this);
//		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//		frame.setSize(371, 364);
//		frame.setPreferredSize(new Dimension(380, 395));
//		frame.pack();
//		frame.setVisible(true);
//	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
			{
				gTimerPanel = new JPanel();
				gTimerPanel.setBounds(56, 63, 280, 329);
				gTimerPanel.setPreferredSize(new Dimension(280,329));
				gTimerPanel.setBorder(BorderFactory.createTitledBorder(""));
			}

			getContentPane().add(gTimerPanel);
			gTimerPanel.setLayout(null);
			{
				jLabel1 = new JLabel();
				gTimerPanel.add(jLabel1);
				jLabel1.setText("Count:");
				jLabel1.setBounds(18, 5, 42, 21);
				{
					jPopupMenu1 = new JPopupMenu();
					setComponentPopupMenu(jLabel1, jPopupMenu1);
					{
						menuRead = new JMenuItem();
						jPopupMenu1.add(menuRead);
						menuRead.setText("Start reading");
						menuRead.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
//								thCount = new Thread()
								thCount.start();
								//TODO add your code for menuRead.actionPerformed
							}
						});
					}
					{
						menuStop = new JMenuItem();
						jPopupMenu1.add(menuStop);
						menuStop.setText("Stop reading");
						menuStop.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
								thCount.interrupt();
								//TODO add your code for menuStop.actionPerformed
							}
						});
					}
				}
			}
			{
				countint = new GInterfaceTerminal(timerFunc.getCIITimer().WORD_COUNT());
				countField = countint.getReadTextField();
				gTimerPanel.add(countField);
				countField.setText("0");
				countField.setBounds(52, 5, 63, 21);
				countField.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
						long tmp = 0; 
						log.debug(""+countint.getAddress());
						try {
							tmp = new Long(countField.getText());
						} catch (Exception e) {
							// TODO: handle exception
							log.error("", e);
						}
					} 
				});
			}
			{
				limit = new GInterfaceTerminal(timerFunc.getCIITimer().WORD_LIMIT());
				jTextField1 = limit.getWriteTextField();
				gTimerPanel.add(jTextField1);
				jTextField1.setText("0");
				jTextField1.setBounds(151, 5, 63, 21);
				jTextField1.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
						long tmp = 0;
						try {
							tmp = new Long(jTextField1.getText());
							log.debug(""+limit.getAddress());
							limit.actionWrite();
							//FIXME test TEMP !!
							FCII_interfaceReader a = (FCII_interfaceReader)readerC;
							a.setExactVal(tmp);
							a.setTempBitsGr(gCII_BITSGroup1);
//							a.set
							// !!
//							jProgressBar.setMaximum((int)tmp);
						} catch (Exception e) {
							// TODO: handle exception
							log.error("", e);
						}
					} 
				});
			}
			{
				jLabel2 = new JLabel();
				gTimerPanel.add(jLabel2);
				jLabel2.setText(": Limit");
				jLabel2.setBounds(215, 5, 42, 21);
			}
			{
				jProgressBar = new ProgressBar();
				jProgressBar.setStringPainted(true);
				jProgressBar.setString("0 %");
				gTimerPanel.add(jProgressBar);
				jProgressBar.setBounds(23, 52, 231, 20);
				jProgressBar.setValue(0);
				jProgressBar.setForeground(new java.awt.Color(0,0,255));
				jProgressBar.setBackground(new java.awt.Color(215,242,247));
				jProgressBar.setFont(new java.awt.Font("Tahoma",0,11));
			}
			{
				gCII_BITSGroup1 = new GCII_BITSGroup(timerFunc.getCIITimer().CII_TIMER());
				gTimerPanel.add(gCII_BITSGroup1.getBitsGroupPanel());
				gCII_BITSGroup1.getBitsGroupPanel().setLocation(35, 79);
				//TEST
				for (final GciiToggleButton tb : gCII_BITSGroup1.getBitsButtons()) {
					tb.addActionListener(new ActionListener() {
					
						@Override
						public void actionPerformed(ActionEvent evt) {
							if (gCII_BITSGroup1.getBitsButtons().get(0).isSelected() && 
									gCII_BITSGroup1.getBitsButtons().get(2).isSelected()) TestHardware.incrementType=2;
						}
					});
				}
				//
			}
			{
				jScrollPaneBits = gCII_BITSGroup1.getBITPanelExtended();
				gTimerPanel.add(jScrollPaneBits);
				jScrollPaneBits.setBounds(0, 105, 280, 224);
				{
					CCII_COMPONENT sub = timerFunc.getCIITimer().CII_TIMER().getChildren().get(0);
					final CCII_ACCESS_INTERF inte = sub.getInterfaces().get(1);
					log.debug(""+sub.getInterfaces().size());
//TODO obsluga typow subcomponentow = np:	if (sub.Name().contains(..REG
					delayField = new GInterfaceTerminal(inte).getWriteTextField();
					gTimerPanel.add(delayField);
					delayField.setText("0");
					delayField.setBounds(98, 28, 70, 21);
					delayField.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
							long tmp = 0;
							try {
								tmp = new Long(delayField.getText());
							} catch (Exception e) {
								// TODO: handle exceptddion
								log.error("", e);
							}
							inte.Write(0, 0, new CIIdata(inte.Width(),tmp));
						}
					});
				}
				{
					jLabel3 = new JLabel(new ImageIcon("D:\\left2.png"));
					gTimerPanel.add(jLabel3);
					jLabel3.setBounds(62, 29, 35, 21);
				}
				{
					jLabel4 = new JLabel();
					gTimerPanel.add(jLabel4);
					jLabel4.setIcon(new ImageIcon(("D:/right.png")));
					jLabel4.setBounds(166, 29, 35, 21);
				}
			}
			pack();
			this.setSize(400, 449);
		} catch (Exception e) {
			log.error("", e);
		}
	}

	public JProgressBar getJProgressBar() {
		return jProgressBar;
	}

	public void setJProgressBar(JProgressBar progressBar) {
		jProgressBar = (ProgressBar)progressBar;
	}
	
	/**
	* Auto-generated method for setting the popup menu for a component
	*/
	private void setComponentPopupMenu(
		final java.awt.Component parent,
		final javax.swing.JPopupMenu menu) {
		parent.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mousePressed(java.awt.event.MouseEvent e) {
				if (e.isPopupTrigger())
					menu.show(parent, e.getX(), e.getY());
			}
			public void mouseReleased(java.awt.event.MouseEvent e) {
				if (e.isPopupTrigger())
					menu.show(parent, e.getX(), e.getY());
			}
		});
	}
	public JPanel getTimerPanel() {
		return gTimerPanel;
	}

	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getCustomPane(java.lang.String)
	 */
	public JPanel getCustomPane(String xmlconfig) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getDefaultPane()
	 */
	public JPanel getDefaultPane() {
		// TODO Auto-generated method stub
		return gTimerPanel;
	}

	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getGCIIName()
	 */
	public String getGCIIName() {
		// TODO Auto-generated method stub
		return null;
	}

}
